import React, { useState } from 'react';
import { Modal, Form, Input, Button, Tabs, message } from 'antd';
import { login, register, User } from '@/services/user';
import { useAuth } from '@/app/auth';

const { TabPane } = Tabs;

interface LoginModalProps {
  visible: boolean;
  onCancel: () => void;
  onSuccess?: () => void;
}

function LoginModal({ visible, onCancel, onSuccess }: LoginModalProps) {
  const [activeTab, setActiveTab] = useState('login');
  const [loading, setLoading] = useState(false);
  const [loginForm] = Form.useForm();
  const [registerForm] = Form.useForm();
  const { login: authLogin } = useAuth();

  // 处理登录
  const handleLogin = async () => {
    try {
      setLoading(true);
      const values = await loginForm.validateFields();
      const result = await login(values.username, values.password);
      
      // 更新身份验证状态
      if (result && result.user && result.token) {
        authLogin({ 
          user: result.user,
          token: result.token 
        });
        
        // 确保关闭模态框
        console.log('登录成功，准备关闭模态框');
        message.success('登录成功');
        try {
          // 使用setTimeout确保在React状态更新后执行关闭
          setTimeout(() => {
            onCancel();
            console.log('登录后模态框已关闭');
            onSuccess?.();
          }, 0);
        } catch (closeError) {
          console.error('关闭模态框失败:', closeError);
        }
      } else {
        throw new Error('登录响应数据不完整');
      }
    } catch (error) {
      console.error('登录失败:', error);
      message.error('登录失败，请检查用户名和密码');
    } finally {
      setLoading(false);
    }
  };

  // 处理注册
  const handleRegister = async () => {
    try {
      setLoading(true);
      const values = await registerForm.validateFields();
      
      // 确认密码检查
      if (values.password !== values.confirmPassword) {
        message.error('两次输入的密码不一致');
        return;
      }
      
      // 不使用解构，避免未使用的变量警告
      const userData: User = {
        username: values.username,
        password: values.password,
        phone: values.phone,
        email: values.email
      };
      
      const result = await register(userData);
      
      // 调试信息
      console.log('注册响应数据:', result);
      
      if (result) {
        // 处理后端返回的两种可能格式
        // 1. {user: UserInfo, token: string} - 直接包含用户信息和token
        // 2. null - 注册成功但没有返回数据，尝试重新登录
        if (result.user && result.token) {
          authLogin({
            user: result.user,
            token: result.token
          });
          
          message.success('注册成功');
          // 关闭模态框
          setTimeout(() => {
            onCancel();
            console.log('模态框已关闭');
            onSuccess?.();
          }, 0);
        } else {
          // 尝试使用注册表单中的用户名和密码进行登录
          const loginResult = await login(values.username, values.password);
          if (loginResult && loginResult.user && loginResult.token) {
            authLogin({
              user: loginResult.user,
              token: loginResult.token
            });
            
            message.success('注册并登录成功');
            // 关闭模态框
            setTimeout(() => {
              onCancel();
              console.log('模态框已关闭');
              onSuccess?.();
            }, 0);
          } else {
            throw new Error('注册成功但登录失败，请尝试手动登录');
          }
        }
      } else {
        throw new Error('注册响应数据为空');
      }
    } catch (error) {
      console.error('注册失败:', error);
      message.error('注册失败，请检查输入信息');
    } finally {
      setLoading(false);
    }
  };

  return (
    <Modal
      title="账户"
      open={visible}
      onCancel={() => {
        console.log('Modal取消按钮被点击');
        onCancel();
      }}
      destroyOnClose
      maskClosable={false}
      keyboard
      footer={null}
    >
      <Tabs activeKey={activeTab} onChange={setActiveTab}>
        <TabPane tab="登录" key="login">
          <Form
            form={loginForm}
            layout="vertical"
            requiredMark={false}
          >
            <Form.Item
              name="username"
              label="用户名"
              rules={[{ required: true, message: '请输入用户名' }]}
            >
              <Input placeholder="请输入用户名" />
            </Form.Item>
            <Form.Item
              name="password"
              label="密码"
              rules={[{ required: true, message: '请输入密码' }]}
            >
              <Input.Password placeholder="请输入密码" />
            </Form.Item>
            <Form.Item>
              <Button 
                type="primary" 
                block 
                onClick={handleLogin} 
                loading={loading && activeTab === 'login'}
              >
                登录
              </Button>
            </Form.Item>
          </Form>
        </TabPane>
        <TabPane tab="注册" key="register">
          <Form
            form={registerForm}
            layout="vertical"
            requiredMark={false}
          >
            <Form.Item
              name="username"
              label="用户名"
              rules={[{ required: true, message: '请输入用户名' }]}
            >
              <Input placeholder="请输入用户名" />
            </Form.Item>
            <Form.Item
              name="password"
              label="密码"
              rules={[{ required: true, message: '请输入密码' }]}
            >
              <Input.Password placeholder="请输入密码" />
            </Form.Item>
            <Form.Item
              name="confirmPassword"
              label="确认密码"
              rules={[{ required: true, message: '请确认密码' }]}
            >
              <Input.Password placeholder="请再次输入密码" />
            </Form.Item>
            <Form.Item
              name="phone"
              label="手机号"
            >
              <Input placeholder="请输入手机号（选填）" />
            </Form.Item>
            <Form.Item
              name="email"
              label="邮箱"
            >
              <Input placeholder="请输入邮箱（选填）" />
            </Form.Item>
            <Form.Item>
              <Button 
                type="primary" 
                block 
                onClick={handleRegister}
                loading={loading && activeTab === 'register'}
              >
                注册
              </Button>
            </Form.Item>
          </Form>
        </TabPane>
      </Tabs>
    </Modal>
  );
}

export default LoginModal; 